package im.composer.media.audio.stream;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.Queue;

/**
 * 
 * @NonThreadSafe
 *
 */
public class LinkedByteArrayInputStream extends InputStream {

	private final Queue<byte[]> queue = new LinkedList<byte[]>();
	private ByteArrayInputStream current = new ByteArrayInputStream(new byte[] {});
	private boolean closed = false;

	@Override
	public int available() throws IOException {
		if (current.available() < 1) {
			byte[] b_arr = queue.poll();
			if(b_arr!=null){
				current = new ByteArrayInputStream(b_arr);
			}else{
				return closed?-1:0;
			}
		}
		return current.available();
	}

	@Override
	public void close() throws IOException {
		closed = true;
	}

	@Override
	public int read() throws IOException {
		if (available() < 1) {
			return -1;
		}
		return current.read();
	}

	public boolean offer(byte[] e) {
		if (e == null) {
			throw new NullPointerException();
		}
		if (e.length < 1) {
			return true;
		}
		return queue.offer(e);
	}

}
